<template>
	<view class="project-container">
		<view class="page-header">
			<text class="page-title">项目位置管理</text>
		</view>
		
		<!-- 加载中提示 -->
		<view class="loading-container" v-if="isLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">加载中...</text>
		</view>
		
		<!-- 项目选择 -->
		<view class="section" v-else>
			<text class="section-title">选择项目</text>
			<view class="project-selector">
				<picker @change="onProjectChange" :value="currentProjectIndex" :range="projectList" range-key="name">
					<view class="picker-content">
						<text class="picker-text">{{ currentProject.name || '请选择项目' }}</text>
						<text class="picker-arrow">▼</text>
					</view>
				</picker>
			</view>
		</view>
		
		<!-- 项目信息 -->
		<view class="section" v-if="currentProject.id && !isLoading">
			<text class="section-title">项目详情</text>
			<view class="project-info">
				<view class="info-item">
					<text class="info-label">项目名称：</text>
					<text class="info-value">{{ currentProject.name }}</text>
				</view>				
				<view class="info-item">
					<text class="info-label">甲方：</text>
					<text class="info-value" :class="'status-' + currentProject.status">{{ currentProject.first_party }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">项目地址：</text>
					<text class="info-value">{{ currentProject.address }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">开始日期：</text>
					<text class="info-value">{{ formatDate(currentProject.start_date) }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">结束日期：</text>
					<text class="info-value">{{ formatDate(currentProject.end_date) }}</text>
				</view>
			</view>
		</view>
		
		<!-- 地图区域 -->
		<view class="section map-section" v-if="!isLoading">
			<view class="section-header">
				<text class="section-title">项目位置</text>
				<button class="btn-small" @tap="getCurrentLocation" :disabled="isGettingLocation">
					{{ isGettingLocation ? '定位中...' : '获取当前位置' }}
				</button>
			</view>
			
			<view class="map-container">
				<map
					id="projectMap"
					class="map"
					:latitude="mapLocation.latitude"
					:longitude="mapLocation.longitude"
					:markers="markers"
					:scale="16"
					show-location
					@tap="onMapTap"
				></map>
			</view>
			
			<view class="location-info" v-if="mapLocation.address">
				<view class="info-item">
					<text class="info-label">当前位置：</text>
					<text class="info-value address-text">{{ mapLocation.address }}</text>
				</view>
			</view>
		</view>
		
		<!-- 保存按钮 -->
		<view class="action-section" v-if="!isLoading">
			<button class="btn-primary" @tap="saveProjectLocation" :disabled="!canSave">保存项目位置</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { projectApi } from '@/common/api'

// 项目列表
const projectList = ref([	
])

// 当前选中的项目
const currentProjectIndex = ref(0)
const currentProject = ref(projectList.value[0] || {})

// 地图相关数据
const mapLocation = ref({
	latitude: 39.909187,
	longitude: 116.397451,
	address: ''
})

const isGettingLocation = ref(false)
const markers = ref([])
const isLoading = ref(false)

// 计算属性：是否可以保存
const canSave = computed(() => {
	return currentProject.value.id && 
		mapLocation.value.latitude && 
		mapLocation.value.longitude
})

// 加载项目列表
const loadProjects = async () => {
	isLoading.value = true
	try {
		const response = await projectApi.getProjects()
		if (response.success && response.data) {
			// 如果API返回数据，使用API数据
			projectList.value = response.data
			if (projectList.value.length > 0) {
				currentProject.value = projectList.value[0]
				currentProjectIndex.value = 0
				
				// 如果项目有位置信息，更新地图
				if (currentProject.value.location) {
					mapLocation.value = {
						...currentProject.value.location
					}
					updateMarkers()
				}
			}
		}
	} catch (error) {
		console.error('获取项目列表失败:', error)
		uni.showToast({
			title: '获取项目列表失败',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
	}
}

// 项目选择变更
const onProjectChange = async (e) => {
	const index = e.detail.value
	currentProjectIndex.value = index
	currentProject.value = projectList.value[index]


	if(currentProject.value.location){
		mapLocation.value = {
			...currentProject.value.location
		}
		updateMarkers()
	}	
}

// 获取当前位置
const getCurrentLocation = async () => {
	isGettingLocation.value = true
	
	try {
		// 获取位置权限
		//await requestLocationPermission()
		
		// 获取当前位置
		const location = await new Promise((resolve, reject) => {
			uni.getLocation({
				type: 'gcj02',
				isHighAccuracy: true, // 高精度定位
				success: resolve,
				fail: (err) => {
					console.error('获取位置失败:', err)
					reject(err)
				}
			})
		})
		
		// 更新位置信息
		mapLocation.value.latitude = location.latitude
		mapLocation.value.longitude = location.longitude
		
		// 更新标记
		updateMarkers()
		
		// // 获取地址信息
		try {
			const res = await new Promise((resolve, reject) => {
				uni.chooseLocation({
					latitude: location.latitude,
					longitude: location.longitude,
					success: resolve,
					fail: reject
				})
			})			
			mapLocation.value.address = res.address || res.name || `位置(${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)})`
		} catch (addrErr) {
			console.error('获取地址信息失败:', addrErr)
			mapLocation.value.address = `位置(${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)})`
		}
		
		uni.showToast({
			title: '位置获取成功',
			icon: 'success'
		})
	} catch (error) {
		console.error('获取位置失败:', error)
		uni.showToast({
			title: '获取位置失败',
			icon: 'error'
		})
	} finally {
		isGettingLocation.value = false
	}
}

// 请求位置权限
const requestLocationPermission = () => {
	return new Promise((resolve, reject) => {
		uni.authorize({
			scope: 'scope.userLocation',
			success: () => {
				// 授权成功
				resolve()
			},
			fail: () => {
				// 授权失败，提示用户在设置中开启
				uni.showModal({
					title: '提示',
					content: '需要获取您的地理位置，请在设置中允许',
					confirmText: '去设置',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							// 打开设置页面
							uni.openSetting({
								success: (settingRes) => {
									if (settingRes.authSetting['scope.userLocation']) {
										resolve()
									} else {
										reject(new Error('用户拒绝授权'))
									}
								},
								fail: () => {
									reject(new Error('打开设置页面失败'))
								}
							})
						} else {
							reject(new Error('用户取消授权'))
						}
					}
				})
			}
		})
	})
}

// 地图点击事件
const onMapTap = (e) => {
	const { latitude, longitude } = e.detail
	
	// 更新位置信息
	mapLocation.value.latitude = latitude
	mapLocation.value.longitude = longitude
	
	// 更新标记
	updateMarkers()
	
	// 设置默认地址格式
	mapLocation.value.address = `位置(${latitude.toFixed(6)}, ${longitude.toFixed(6)})`
	
	// 打开位置选择器
	uni.showModal({
		title: '位置信息',
		content: '是否打开位置选择器获取详细地址？',
		success: (res) => {
			if (res.confirm) {
				uni.chooseLocation({
					latitude,
					longitude,
					success: (res) => {
						// 更新地址信息
						if (res.address || res.name) {
							mapLocation.value.address = res.address || res.name
							
							// 如果返回的位置与选择的不同，更新位置和标记
							if (res.latitude && res.longitude) {
								mapLocation.value.latitude = res.latitude
								mapLocation.value.longitude = res.longitude
								updateMarkers()
							}
						}
					},
					fail: (err) => {
						console.error('获取位置详情失败:', err)
					}
				})
			}
		}
	})
}

// 更新地图标记
const updateMarkers = () => {
	markers.value = [{
		id: 1,
		latitude: mapLocation.value.latitude,
		longitude: mapLocation.value.longitude,
		iconPath: '/static/location-marker.png',
		width: 32,
		height: 32
	}]
}

// 保存项目位置
const saveProjectLocation = async () => {
	if (!currentProject.value.id) {
		uni.showToast({
			title: '请先选择项目',
			icon: 'none'
		})
		return
	}
	
	if (!mapLocation.value.latitude || !mapLocation.value.longitude) {
		uni.showToast({
			title: '请先获取或选择位置',
			icon: 'none'
		})
		return
	}
	
	try {
		// 保存位置到当前项目
		currentProject.value.location = {
			latitude: mapLocation.value.latitude,
			longitude: mapLocation.value.longitude,
			address: mapLocation.value.address
		}
		
		// 更新项目列表中的项目
		projectList.value[currentProjectIndex.value] = { ...currentProject.value }
		
		// 保存到服务器
		const response = await projectApi.updateProjectLocation({
			project_id: currentProject.value.id,
			location: {
				latitude: mapLocation.value.latitude,
				longitude: mapLocation.value.longitude,
				address: mapLocation.value.address
			}
		})
		
		if (response.success) {
			uni.showToast({
				title: '项目位置已保存',
				icon: 'success'
			})
		} else {
			throw new Error(response.message || '保存失败')
		}
	} catch (error) {
		console.error('保存项目位置失败:', error)
		uni.showToast({
			title: '保存失败，请重试',
			icon: 'none'
		})
	}
}

// 格式化日期
const formatDate = (dateString) => {
	if (!dateString) return ''
	
	const date = new Date(dateString)
	return date.toISOString().split('T')[0]
}

// 获取状态文本
const getStatusText = (status) => {
	const statusMap = {
		'planning': '规划中',
		'ongoing': '进行中',
		'completed': '已完成',
		'paused': '已暂停'
	}
	
	return statusMap[status] || status
}

// 页面加载
onMounted(() => {
	// 初始化地图标记
	updateMarkers()
	
	// 加载项目列表
	loadProjects()
})
</script>

<style scoped>
.project-container {
	padding: 32rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.page-header {
	margin-bottom: 32rpx;
}

.page-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #2B5BA1;
}

.section {
	background: white;
	border-radius: 16rpx;
	padding: 32rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
	display: block;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.project-selector {
	background: #f8f9fa;
	border-radius: 8rpx;
	border: 1px solid #e9ecef;
}

.picker-content {
	padding: 24rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.picker-text {
	font-size: 30rpx;
	color: #333;
}

.picker-arrow {
	font-size: 24rpx;
	color: #999;
}

.project-info {
	background: #f8f9fa;
	border-radius: 8rpx;
	padding: 24rpx;
}

.info-item {
	display: flex;
	margin-bottom: 16rpx;
}

.info-item:last-child {
	margin-bottom: 0;
}

.info-label {
	font-size: 28rpx;
	color: #666;
	width: 180rpx;
	flex-shrink: 0;
}

.info-value {
	font-size: 28rpx;
	color: #333;
	flex: 1;
}

.status-ongoing {
	color: #2B5BA1;
}

.status-planning {
	color: #ff9800;
}

.status-completed {
	color: #4caf50;
}

.status-paused {
	color: #f44336;
}

.map-section {
	padding-bottom: 24rpx;
}

.map-container {
	width: 100%;
	height: 500rpx;
	border-radius: 8rpx;
	overflow: hidden;
	margin-bottom: 24rpx;
}

.map {
	width: 100%;
	height: 100%;
}

.location-info {
	background: #f8f9fa;
	border-radius: 8rpx;
	padding: 16rpx 24rpx;
}

.address-text {
	word-break: break-all;
}

.action-section {
	margin-top: 40rpx;
	margin-bottom: 80rpx;
}

.btn-primary {
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 32rpx;
	font-size: 32rpx;
	font-weight: 500;
	width: 100%;
}

.btn-primary:active {
	background: #1e4b8f;
}

.btn-primary[disabled] {
	background: #a0b4d0;
}

.btn-small {
	background: #e9ecef;
	color: #495057;
	font-size: 24rpx;
	padding: 8rpx 20rpx;
	border-radius: 8rpx;
	border: none;
}

.btn-small:active {
	background: #dee2e6;
}

.btn-small[disabled] {
	color: #adb5bd;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60rpx 0;
	background: white;
	border-radius: 16rpx;
	margin-bottom: 32rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.loading-spinner {
	width: 60rpx;
	height: 60rpx;
	border: 6rpx solid #f3f3f3;
	border-top: 6rpx solid #2B5BA1;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes spin {
	0% { transform: rotate(0deg); }
	100% { transform: rotate(360deg); }
}
</style> 